﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Web.Mvc;
using Xenta.Attributes;
using Xenta.Utils;
using Xenta.Web.Controllers;

namespace Xenta.Web.Areas.Store.Controllers
{
    public sealed class ItemController : ExtController
    {
        #region GET/POST Actions

        [HttpGet]
        public ActionResult Index(int? page,
            string searchTerm,
            int? sellerID,
            int? categoryID, 
            int? supplierID,
            int? itemID,
            string attributeIDs,
            string priceFrom,
            string priceTo,
            string sortBy,
            bool? sortDesc)
        {
            string salesSortBy = String.Empty;
            string catalogSortBy = String.Empty;
            page = page.HasValue ? page.Value : 0;
            sortBy = StringHelper.EnsureNotNull(sortBy).Trim()
                .ToLowerInvariant();
            dynamic m = new ExpandoObject();

            switch(sortBy)
            {
                case "rating":
                    catalogSortBy = "RatingAverage";
                    break;
                case "price":
                    salesSortBy = "Price";
                    break;
                default:
                    salesSortBy = "CreatedOn";
                    break;
            }
            m.CountPerPage = Svc.Config(Par.In("WebPortal").Of("Store").Of(this).Group("Index").Name("Count"), 12);
            m.Index = Svc.ProcessOperation("SearchSalesItemsOverCatalog", new
            {
                LanguageID = JDM.Int32(Svc.Localization.Language.EntityID),
                Term = new
                {
                    Expression = String.IsNullOrWhiteSpace(searchTerm) ?
                        String.Empty :
                        String.Format("%{0}%", searchTerm)
                },
                SellerID = sellerID,
                CategoryID = categoryID,
                SupplierID = supplierID,
                ItemID = itemID,
                AttributeIDs = String.IsNullOrWhiteSpace(attributeIDs) ? null : attributeIDs.Split(',').Select(x => x.ParseAs<Int32>()),
                AvailableOn = DateTime.UtcNow,
                PriceFrom = String.IsNullOrWhiteSpace(priceFrom) ? null : (decimal?)Svc.Price(priceFrom),
                PriceTo = String.IsNullOrWhiteSpace(priceTo) ? null : (decimal?)Svc.Price(priceTo),
                Index = page * 12,
                Count = 12,
                CatalogFlagMask = "Active",
                SalesSortBy = !String.IsNullOrWhiteSpace(salesSortBy) 
                    ? new [] 
                    {
                        salesSortBy 
                    }
                    : null,
                CatalogSortBy = !String.IsNullOrWhiteSpace(catalogSortBy) 
                    ? new []
                    {
                        catalogSortBy
                    }
                    : null,
                SortDir = !sortDesc.HasValue || sortDesc.Value
                    ? "Descending"
                    : "Ascending"
            }, new
            {
                DisclosureLevel = "Extended",
                DisclosureOptions = new Dictionary<String, String>
                {
                    { "TranslatedTo", JDM.String(Svc.Localization.Language.Code) }
                }.Unload()
            });
            return View(m);
        }

        [HttpGet, RestoreState]
        public ActionResult Show(int id)
        {
            dynamic m = Svc.ProcessOperation("GetSalesItem", new
            {
                EntityID = id
            }, new
            {
                DisclosureLevel = "Entire",
                DisclosureOptions = new Dictionary<String, String>
                {
                    { "TranslatedTo", JDM.String(Svc.Localization.Language.Code) }
                }.Unload()
            });
            if(m == null)
                return HttpNotFound();
            return View(m);
        }

        [HttpGet]
        public ActionResult GoTo(string sku)
        {
            dynamic m = Svc.ProcessOperation("GetSalesItemBySKU", new
            {
                SKU = sku
            });
            if(m == null)
                return HttpNotFound();
            return RedirectToAction(Loc.Act("Show").Set(new
            {
                id = JDM.Int32(m.EntityID)
            }).Localized());
        }

        #endregion

        #region Child Actions

        [ChildActionOnly]
        public ActionResult _Promoted()
        {
            var m = Svc.ProcessOperation("SearchSalesItemsOverCatalog", new
            {
                LanguageID = JDM.Int32(Svc.Localization.Language.EntityID),
                Count = Svc.Config(Par.In("WebPortal").Of("Store").Of(this).Group("_Promoted").Name("Count"), 12),
                CatalogFlagMask = "Active,Promoted",
                SalesSortBy = new[] 
                {
                    "CreatedOn"
                },
                SortDir = "Descending"
            }, new
            {
                DisclosureLevel = "Extended",
                DisclosureOptions = new Dictionary<String, String>
                {
                    { "TranslatedTo", JDM.String(Svc.Localization.Language.Code) }
                }.Unload()
            });
            return View(m);
        }

        [ChildActionOnly]
        public ActionResult _Latest(int? sellerID)
        {
            var m = Svc.ProcessOperation("SearchSalesItemsOverCatalog", new
            {
                LanguageID = JDM.Int32(Svc.Localization.Language.EntityID),
                Count = Svc.Config(Par.In("WebPortal").Of("Store").Of(this).Group("_Latest").Name("Count"), 12),
                SellerID = sellerID,
                CatalogFlagMask = "Active",
                SalesSortBy = new[] 
                {
                    "CreatedOn"
                },
                SortDir = "Descending"
            }, new
            {
                DisclosureLevel = "Extended",
                DisclosureOptions = new Dictionary<String, String>
                {
                    { "TranslatedTo", JDM.String(Svc.Localization.Language.Code) }
                }.Unload()
            });
            return View(m);
        }

        [ChildActionOnly]
        public ActionResult _Filter(int? sellerID, 
            int? categoryID, 
            int? supplierID, 
            int? itemID,
            string attributeIDs)
        {
            dynamic m = new ExpandoObject();
            m.Selected = new ExpandoObject();
            m.Filter = new ExpandoObject();

            //category
            m.Selected.Category = !categoryID.HasValue ? null : Svc.ProcessOperation("GetCatalogCategory", new
            {
                EntityID = categoryID.Value
            }, new
            {
                DisclosureLevel = "Entire",
                DisclosureOptions = new Dictionary<String, String>
                {
                    { "TranslatedTo", JDM.String(Svc.Localization.Language.Code) }
                }.Unload()
            });
            m.Filter.Categories = Svc.ProcessOperation("SearchCatalogCategories", new
            {
                ParentID = categoryID.HasValue ? categoryID.Value : 0,
                FlagMask = "Active"
            }, new
            {
                DisclosureLevel = "Base",
                DisclosureOptions = new Dictionary<String, String>
                {
                    { "TranslatedTo", JDM.String(Svc.Localization.Language.Code) }
                }.Unload()
            }).Items;

            //seller
            m.Selected.Seller = !sellerID.HasValue ? null : Svc.ProcessOperation("GetSeller", new
            {
                EntityID = sellerID.Value
            }, new
            {
                DisclosureLevel = "Base"
            });

            //supplier
            m.Selected.Supplier = !supplierID.HasValue ? null : Svc.ProcessOperation("GetCatalogSupplier", new
            {
                EntityID = supplierID.Value
            }, new
            {
                DisclosureLevel = "Base",
                DisclosureOptions = new Dictionary<String, String>
                {
                    { "TranslatedTo", JDM.String(Svc.Localization.Language.Code) }
                }.Unload()
            });

            //item
            m.Selected.Item = !itemID.HasValue ? null : Svc.ProcessOperation("GetCatalogItem", new
            {
                EntityID = itemID.Value
            }, new
            {
                DisclosureLevel = "Base",
                DisclosureOptions = new Dictionary<String, String>
                {
                    { "TranslatedTo", JDM.String(Svc.Localization.Language.Code) }
                }.Unload()
            });

            //attributes
            m.Selected.Attributes = new List<dynamic>();
            if(!String.IsNullOrWhiteSpace(attributeIDs))
            {
                foreach(var i in attributeIDs.Split(',').Select(x => x.ParseAs<Int32>()))
                {
                    m.Selected.Attributes.Add(Svc.ProcessOperation("GetLookupAttribute", new
                    {
                        EntityID = i
                    }, new
                    {
                        DisclosureLevel = "Base",
                        DisclosureOptions = new Dictionary<String, String>
                        {
                            { "TranslatedTo", JDM.String(Svc.Localization.Language.Code) }
                        }.Unload()
                    }));
                }
            }
            m.Filter.Attributes = m.Selected.Category != null
                ? m.Selected.Category.Attributes
                : Enumerable.Empty<dynamic>();
            return PartialView(m);
        }

        #endregion
    }
}
